/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.java.tools;

import java.io.File;

import java.lang.reflect.Method;

import java.net.URL;
import java.net.URLClassLoader;


public class ScriptRunner extends AbstractCodeGenerator implements Runner {
    String mFileTop = System.getProperty("user.dir") + File.separator;
    String mOutputMessage;
    String mStatement = "System.out.println(new Date());";

    /**
     * Creates a new ScriptRunner object.
     *
     * @param pPackageName Parameter
     * @param pClassName Parameter
     */
    public ScriptRunner(String pPackageName, String pClassName) {
        super(pPackageName, pClassName);
    }

    //interface needed for CodeGenerator
    public String getCode() {
        StringBuffer code = new StringBuffer();

        if ((getPackageName() != null) && (getPackageName().length() != 0)) {
            code.append("package " + getPackageName() + ";\n");
        }

        code.append("/** \n").append("* This code is generated by DummyCG, please do not change it manually \n")
            .append("**/\n").append("import java.util.*;\n").append("import java.math.*;\n")
            .append("public class " + getClassName() + "\n{")
            .append("\n\tpublic static void main(String[] args) throws Exception \n\t{")
            .append("\n\t\t" + mStatement + "\n").append("\t}\n}\n");

        return code.toString();
    }

    public String getOutputMessage() {
        return mOutputMessage;
    }

    //interface needed for CodeGenerator
    public Runner getRunner() {
        return this;
    }

    //interface of runner
    public void execute() {
        try {
            //we need reload the class
            Class thisClass = loadClass(mFileTop, getClassQName());

            if (thisClass == null) {
                return;
            }

            Method main = thisClass.getDeclaredMethod("main", new Class[] { String[].class });
            main.invoke(null, new Object[] { new String[0] });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void execute(String pStatement) {
        try {
            DynamicJava mtc = new DynamicJava(this, mFileTop);
            mStatement = pStatement;
            mtc.save();

            if (mtc.compile()) {
                mtc.execute();
            }

            mOutputMessage = mtc.getErrorStack();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Class loadClass(String path, String className)
        throws ClassNotFoundException {
        try {
            URL[] serverURLs = new URL[] { new URL("file://" + path + "/") };
            URLClassLoader cl = new URLClassLoader(serverURLs, Thread.currentThread().getContextClassLoader());

            return cl.loadClass(className);
        } catch (Exception e) {
            e.printStackTrace();

            //...
        }

        return null;
    }

}
